/*
 * Copyright (c)  2020~2021, EnnCloud/SA
 * All rights reserved.
 * Project:ep-service-center
 * Id: SpringContextUtil.java   2021-05-24 16:46:46
 * Author: Evan
 */
package com.alibaba.gao.delayQueue;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2020~2021
 * </p>
 * <p>
 * Company/Department: EnnCloud/SA
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2021-05-24 16:46:46
 * @since V1.0
 */
@Configuration
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
        return applicationContext.getBean(name, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getBean(clazz, applicationContext);
    }

    public static <T> T getBean(Class<T> clazz, ApplicationContext ctx) {
        Map<String, T> map = ctx.getBeansOfType(clazz);
        if (map.size() == 0) {
            return null;
        } else if (map.size() > 1) {
            throw new IllegalArgumentException("bean is not unique.");
        }
        return map.values().iterator().next();
    }
}

